(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
	typeof define === 'function' && define.amd ? define(factory) :
    // here name is your name
  (global.util = factory());
// window can use this if not strict
}(window, (function () { 
    'use strict';
    let gll={
        //
        host:'',
        beforeAjax(){

        },
        afterAjax(){

        },
        ajaxError(e){
            console.log(e)
        },
        ajaxHeaders:{},
        // ajax
        ajax(obj){
            if (!obj.url){
                console.error('arguments must have a url!');
            }

            obj.url=this.host+obj.url;
            obj.method=(obj.method || 'get').toUpperCase();
            obj.data=obj.data || {};

            if (obj.method === 'GET' || obj.method === 'DELETE')
            {
                obj.url+=this.obj2query(obj.data);
            }
            if (!obj.custom){
                this.beforeAjax()
            }

            return new Promise((resolve,reject)=>{
                let xhr=new XMLHttpRequest();
                xhr.onreadystatechange=()=>{
                    if (xhr.readyState===4)
                    {
                        if (!obj.custom){
                            this.afterAjax()
                        }
                        if (xhr.status<400)
                        {
                            resolve(JSON.parse(xhr.responseText));
                        }else{
                            this.ajaxError(xhr);
                            reject(xhr);
                        }
                    }
                }

                xhr.open(obj.method,obj.url,true);
                xhr.setRequestHeader('Content-Type','application/json');
                for (let key in this.ajaxHeaders){
                    xhr.setRequestHeader(key,this.ajaxHeaders[key]);
                }

                if (obj.method === 'POST' || obj.method === 'PUT'){
                    xhr.send(JSON.stringify(obj.data));
                }else{
                    xhr.send(null);
                }
            });
        },
        toDelKey:['custom','token'],
        get(url,obj){
            let sendObj={
                method:'GET',
                url:url
            }

            if (typeof obj !== 'undefined') {
                for (let item of this.toDelKey){
                    if (typeof obj[item] !== 'undefined') {
                        sendObj[item] = obj[item]
                        delete obj[item]
                    }
                }
                
                sendObj.data = obj
            }

            return this.ajax(sendObj)
        },
        post(url,obj){
            let sendObj={
                method:'POST',
                url:url
            }

            if (typeof obj !== 'undefined') {
                for (let item of this.toDelKey){
                    if (typeof obj[item] !== 'undefined') {
                        sendObj[item] = obj[item]
                        delete obj[item]
                    }
                }
                
                sendObj.data = obj
            }

            return this.ajax(sendObj)
        },
        getToken(){

        },

        // default
        getQuery(key){
            let searchStr=window.location.search
            let resObj={}
            if (searchStr){
                searchStr=searchStr.replace('?','')
                let searchArr=searchStr.split('&')
                for (let item of searchArr){
                    let itemArr=item.split('=')
                    resObj[itemArr[0]]=itemArr[1]
                }

                if (key){
                    return resObj[key]
                }else{
                    return resObj
                }
            }else{
                return null
            }
        },
        getParam(key){
            let url=window.location.href;
            let url_length=url.length;
            let startPos=url.indexOf(key+'/')+2;
            let res='';
            for (let i=startPos;i<url_length;i++){
                if (url[i]==='/'){
                    return res
                }else{
                    res+=url[i]
                }
            }
            return res
        },
        obj2query(obj){
            let res='?';
            for (let key in obj){
                res+=key.toString()+'='+obj[key].toString()+'&'
            }
            res=res.substr(0,res.length-1);
            return res;
        },
        rnd(min,max){
            return Math.round((Math.random()*(max-min)+min));
        },
        hash(){
          return Math.random().toString(16).substring(2);          
        },
        uuid(){
            let str='1a2b3c4d5e6f7g8h9i0jklmnopqrstuvwxyz'.split('');
            let uuid=[];
            for (let i=0;i<36;i++)
            {
                uuid.push(str[this.rnd(0,35)]);
            }
            uuid[8]=uuid[13]=uuid[18]=uuid[23]='-';
            return uuid.join('');
        },
        getCmd(line){
            if (!line){
                return null;
            }

            let reg=/^-{1,2}|\s+-{1,2}/gi;

            if (!reg.test(line)){
                return line;
            }

            let obj=null;
            let array=line.split(reg);
            for (let item of array){
                if (item===''){
                    continue;
                }else{
                    let pos=item.indexOf(' ');
                    let key=item.substring(0,pos);
                    let value=item.substring(pos+1);

                    if (!obj){
                        obj={};
                    }

                    obj[key]=value;
                }
            }
            return obj;
        },
        isWx(){
            return window.navigator.userAgent.indexOf("MicroMessenger")!==-1;
        },
        jsApiList:[
            "updateAppMessageShareData",
            "updateTimelineShareData",
            "onMenuShareTimeline",
            "onMenuShareAppMessage",
            "onMenuShareQQ",
            "onMenuShareWeibo",
            "onMenuShareQZone",
            "startRecord",
            "stopRecord",
            "onVoiceRecordEnd",
            "playVoice",
            "pauseVoice",
            "stopVoice",
            "onVoicePlayEnd",
            "uploadVoice",
            "downloadVoice",
            "chooseImage",
            "previewImage",
            "uploadImage",
            "downloadImage",
            "translateVoice",
            "getNetworkType",
            "openLocation",
            "getLocation",
            "hideOptionMenu",
            "showOptionMenu",
            "hideMenuItems",
            "showMenuItems",
            "hideAllNonBaseMenuItem",
            "showAllNonBaseMenuItem",
            "closeWindow",
            "scanQRCode",
            "chooseWXPay",
            "openProductSpecificView",
            "addCard",
            "chooseCard",
            "openCard"
        ],
        // 线程锁
        sleepAsync(s){
            let now=new Date().getTime();
            let to=now+s;
            while(now<to){
                now=new Date().getTime();
            }
        },
        // 异步
        sleep(s){
            return new Promise((resolve)=>{
                setTimeout(resolve,s)
            })
        },

        // UI

        alert(obj){
            obj=obj || {}
            obj.confirmText=obj.confirmText || '确定';
            obj.cancelText=obj.cancelext || '取消';
            obj.confirmColor=obj.confirmColor || "#3385ff";
            
            if (typeof obj.title==='undefined'){
              obj.title=''
            }
      
            if (typeof obj.content==='undefined'){
              obj.content='确定?'
            }

            if (typeof obj.maskClick==='undefined'){
                obj.maskClick=false
            }

            if (typeof obj.cancel==='undefined'){
                obj.cancel=false
            }
      
            let divid=Math.random().toString(16).substring(2);
            let body=document.getElementsByTagName('body')[0];
            let div=document.createElement('div');
            div.id=divid
            div.className="com-mask"
            div.innerHTML=`
            <div class="com-box">
              <div class="com-title">
                  ${obj.title}
              </div>
              <div class="com-content">
                ${obj.content}
              </div>
              <div class="com-ctrl">
                <a id="${divid}-no" class="com-no${obj.cancel?'':' hide'}" href="javascript:;">${obj.cancelText}</a>
                <a id="${divid}-yes" class="com-yes"href="javascript:;" style="background-color:${obj.confirmColor};">${obj.confirmText}</a>
              </div>
            </div>
            `
            body.appendChild(div)
            setTimeout(()=>{
              div.className="com-mask dark"
            },1)
      
            return new Promise((resolve,reject)=>{
              let nobtn=document.getElementById(divid+'-no');
              let yesbtn=document.getElementById(divid+'-yes');
      
              let noHandle=function(event){
                event.stopPropagation()
                uninstall()
                reject('cancel')
              }
      
              let yesHandle=function(event){
                event.stopPropagation()
                uninstall()
                resolve(true)
              }
      
              let maskHandle=function(){
                uninstall()
                reject('mask')
              }
      
              yesbtn.addEventListener('click',yesHandle,false)
              nobtn.addEventListener('click',noHandle,false)
              if (obj.maskClick){
                div.addEventListener('click',maskHandle,false)
              }
              
      
              function uninstall(){
                yesbtn.removeEventListener('click',yesHandle,false)
                nobtn.removeEventListener('click',noHandle,false)
                if (obj.maskClick){
                    div.removeEventListener('click',maskHandle,false)
                }
                body.removeChild(div)
              }
            })
      
        },
        vueHide(){
            let body=document.getElementsByTagName('body')[0];
            body.removeChild(document.getElementById('vue-mask'));
        },
        loading(title,id){
            let body=document.getElementsByTagName('body')[0];
            let div=document.createElement('div');
            if (!id){
                div.id=id
            }
            if (!title){
                title=''
            }
            div.className="com-loading"
            div.innerHTML=`
            <div class="rotdiv">
            </div>
            <div class="title">${title}</div>
            `;
            body.appendChild(div)
        },
        hideLoading(id){
            let body=document.getElementsByTagName('body')[0];
            if (id){
                body.removeChild(document.getElementById(id))
            }else{
                for (let item of document.querySelectorAll(".com-loading")){
                    body.removeChild(item)
                }
            }
        }
    };
    return gll


})))